import { TENCENT_MAP_CONFIG, validateApiKey } from './config'

// 全局变量，确保SDK只加载一次
let tencentMapSDKPromise: Promise<any> | null = null

/**
 * 检查腾讯地图SDK是否已加载
 */
function isTencentMapSDKLoaded(): boolean {
  return typeof (window as any).TMap !== 'undefined'
}

/**
 * 等待腾讯地图对象完全初始化
 */
function waitForTencentMap(maxRetries = 10, interval = 100): Promise<any> {
  return new Promise((resolve, reject) => {
    let retries = 0
    
    const checkTMap = () => {
      if ((window as any).TMap && (window as any).TMap.Map) {
        resolve((window as any).TMap)
        return
      }
      
      retries++
      if (retries >= maxRetries) {
        reject(new Error('腾讯地图对象初始化超时'))
        return
      }
      
      setTimeout(checkTMap, interval)
    }
    
    checkTMap()
  })
}

/**
 * 动态加载腾讯地图SDK
 */
export function loadTencentMapSDK(): Promise<any> {
  // 如果已经加载过，直接返回缓存的Promise
  if (tencentMapSDKPromise) {
    return tencentMapSDKPromise
  }

  // 如果SDK已经存在，直接返回
  if (isTencentMapSDKLoaded()) {
    tencentMapSDKPromise = Promise.resolve((window as any).TMap)
    return tencentMapSDKPromise
  }

  // 创建加载Promise
  tencentMapSDKPromise = new Promise((resolve, reject) => {
    // 检查API Key
    if (!validateApiKey()) {
      reject(new Error('请配置有效的腾讯地图API Key'))
      return
    }

    // 创建script标签
    const script = document.createElement('script')
    script.type = 'text/javascript'
    script.async = true
    script.defer = true
    
    // 构建API URL
    const apiUrl = `${TENCENT_MAP_CONFIG.apiUrl}?v=${TENCENT_MAP_CONFIG.version}&key=${TENCENT_MAP_CONFIG.apiKey}&libraries=geometry,drawing,visualization`
    script.src = apiUrl

    // 脚本加载成功
    script.onload = async () => {
      try {
        // 等待TMap对象完全初始化
        const TMap = await waitForTencentMap()
        console.log('腾讯地图SDK加载成功')
        resolve(TMap)
      } catch (error) {
        console.error('腾讯地图SDK初始化失败:', error)
        reject(error)
      }
    }

    // 脚本加载失败
    script.onerror = (error) => {
      console.error('腾讯地图SDK脚本加载失败:', error)
      reject(new Error('腾讯地图SDK脚本加载失败'))
    }

    // 添加到页面
    document.head.appendChild(script)
  })

  return tencentMapSDKPromise
}

/**
 * 获取腾讯地图配置
 */
export function getTencentMapConfig() {
  return { ...TENCENT_MAP_CONFIG }
}

/**
 * 设置腾讯地图API Key
 */
export function setTencentMapApiKey(apiKey: string) {
  TENCENT_MAP_CONFIG.apiKey = apiKey
  // 重置Promise，下次加载时使用新的API Key
  tencentMapSDKPromise = null
}

/**
 * 检查API Key是否已配置
 */
export function isApiKeyConfigured(): boolean {
  return validateApiKey()
}